# app.py
from flask import Flask, request, render_template, jsonify
import requests
import os
from PIL import Image
import base64

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'

API_KEY = "ReYneqYKuZlE2wJcnz58nIdJ"
SECRET_KEY = "rhkJw5OSDGuAUv9zJEbPMcHg7qeAbtOo"


def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def recognize_text(file_path):
    access_token = get_access_token()
    url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token={access_token}"

    with open(file_path, 'rb') as f:
        img = f.read()
    img_base64 = base64.b64encode(img).decode('utf-8')

    payload = {
        'image': img_base64,
        'detect_direction': 'false',
        'paragraph': 'false',
        'probability': 'false'
    }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    response = requests.post(url, headers=headers, data=payload)
    result = response.json()

    # 打印响应内容以便调试
    print(result)

    return result


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'image' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['image']

    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])

    file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
    file.save(file_path)

    result = recognize_text(file_path)

    if 'words_result' in result:
        text = '\n'.join([word['words'] for word in result['words_result']])
        return jsonify({'text': text})
    else:
        # 如果响应中没有'words_result'键，返回错误信息
        return jsonify({'error': 'OCR failed', 'details': result}), 500


if __name__ == '__main__':
    app.run(debug=True)
